package fr.neyb.wesb.core.data.descriptors.field.impl;

import java.util.Comparator;
import java.util.regex.Pattern;

import fr.neyb.wesb.core.data.compare.Order;
import fr.neyb.wesb.core.data.compare.comparators.TextableFieldComparator;
import fr.neyb.wesb.core.data.content.Field;
import fr.neyb.wesb.core.data.content.TextableField;
import fr.neyb.wesb.core.data.descriptors.field.ComparableTypedFieldDescriptor;

public class TextFieldDescriptor extends AbstractFieldDescritor<TextableField>
		implements ComparableTypedFieldDescriptor {

	private static class patternValidator implements CSValidator<TextableField> {
		private final Pattern p;

		public patternValidator(Pattern p) {
			this.p = p;
		}

		@Override
		public boolean validate(TextableField field) {
			return p.matcher(((TextableField) field).toString()).find();
		}
	}

	private static class lengthValidator implements CSValidator<TextableField> {

		private int minLength = -1;
		private int maxLength = -1;

		public void setMin(int newMin) {
			minLength = newMin;
		}

		public void setMax(int newMax) {
			maxLength = newMax;
		}

		@Override
		public boolean validate(TextableField field) {
			CharSequence cs = ((TextableField) field).toString();
			return (minLength < 0 || cs.length() >= minLength)
					&& (maxLength < 0 || cs.length() <= maxLength);
		}
	}

	private final SimpleComparableTypedFieldDescriptorImpl SCTFDImpl = new SimpleComparableTypedFieldDescriptorImpl(
			TextableFieldComparator.class);

	public TextFieldDescriptor() {
		super(TextableField.class, new lengthValidator());
		addvalidator(new lengthValidator());
	}

	public void addMinLengthValidator(int min) {
		((lengthValidator) getOmniValidator(0)).setMin(min);
	}

	public void addMaxLengthValidator(int max) {
		((lengthValidator) getOmniValidator(0)).setMax(max);
	}

	public void addValidator(Pattern val) {
		addvalidator(new patternValidator(val));
	}

	@Override
	public Comparator<Field> getComparator(Order o) {
		return SCTFDImpl.getComparator(o);
	}

	@Override
	public Class<? extends Comparator<Field>> getComparatorClass() {
		return SCTFDImpl.getComparatorClass();
	}

	@Override
	public void setComparatorClass(Class<? extends Comparator<Field>> compClass) {
		SCTFDImpl.setComparatorClass(compClass);
	}
}
